package com.xuecheng.checkcode.service.impl;

import com.xuecheng.checkcode.service.FindPasswordService;
import com.zmt.xuechengplusbase.exception.xuechengplusException;
import com.zmt.xuechengplusbase.model.RestResponse;
import com.zmt.xuechengplusbase.utils.RandomStringUtil;
import com.zmt.xuechengplusbase.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@Service
public class FindPasswordServiceImpl implements FindPasswordService {

    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String sendEmail;


    /**
     * 首先要进行参数判断是手机号还是邮箱
     * @param param
     * @return
     */
    @Override
    public String sendCode(String param) {
        if (StringUtil.isEmpty(param)){
            xuechengplusException.cast("请输入手机号或邮箱");
        }
        String s = regex_param(param);
        String code = RandomStringUtil.getRandomString(6);
        if (s.equals("phone")){
            //说明手机号验证。
            //这里引用base的工具类会导致权限问题吗？
            log.debug("手机验证找回密码，验证码位{}",code);
            //TODO 保存redis进行验证
            return "200";
        }
        if (s.equals("email")){
            //说明邮箱验证
            sendMsg(param,"找回密码","您的验证码为"+code+"，请在五分钟内进行验证");
            //TODO 保存redis进行验证
            return "200";
        }
        return "请正确输入手机号或邮箱";
    }


    /**
     * 对格式进行判断
     * @param param
     * @return
     */
    private String regex_param(String param){
        String regex_phone="^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\\\d{8}$";
        Pattern compile = Pattern.compile(regex_phone);
        Matcher matcher_phone = compile.matcher(param);
        boolean matches = matcher_phone.matches();
        if (!matches){
            //说明不是手机验证
            String regex_email="^(\\w+([-.][A-Za-z0-9]+)*){3,18}@\\w+([-.][A-Za-z0-9]+)*\\.\\w+([-.][A-Za-z0-9]+)*$";
            boolean matcher_email = Pattern.matches(regex_email, param);
            if (matcher_email){
                return "email";
            }
            //不是手机号也不是邮箱号
            return "error";
        }
        return "phone";
    }

    /**
     * 发送邮件
     * @param to
     * @param subject
     * @param text
     */
    private void sendMsg(String to, String subject, String text) {
        //发送简单邮件，简单邮件不包括附件等别的
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(sendEmail);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(text);
        //发送邮件
        javaMailSender.send(message);
    }
}
